#include <iostream>
#include <Winsock2.h>
#include <WS2tcpip.h>
#include "udp.h"

#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#pragma comment(lib, "ws2_32.lib")

UDP::~UDP() {
    closesocket(sender);
}

bool UDP::open(const char* ip, int port) {
    try {
        auto wsad = WSADATA();
        int ret = WSAStartup(MAKEWORD(2, 2), &wsad);
        if (ret != 0) {
            throw std::string("Win socket initialization failed!\n");
        }
        sender = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        receiver.sin_family = AF_INET;
        receiver.sin_port = htons(port);
        inet_pton(AF_INET, ip, (void*)&receiver.sin_addr.S_un.S_addr);
        printf("Open UDP to %s:%d\n", ip, port);
        return true;
    }
    catch (...) {
        return false;
    }
}

void UDP::send(char* data, int length) {
    try {
        sendto(sender, data, length, 0, (sockaddr*)&receiver, sizeof(receiver));
    }
    catch (...) {}
}
